package com.iwork.platform.util;

import com.google.common.collect.Lists;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.util.Assert;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * Miscellaneous utilities for web applications.
 *
 * @author L.cm
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class CookiesUtils {

    /**
     * 读取cookie
     *
     * @param request
     * @param name
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String name) {
        Assert.notNull(request, "Request must not be null");
        Optional<Cookie> cookieOptl = Lists.newArrayList(request.getCookies()).stream().filter(item -> name.equals(item.getName())).findFirst();
        if (cookieOptl.isPresent()) {
            return cookieOptl.get().getValue();
        }
        return null;
    }

    /**
     * 清除 某个指定的cookie
     *
     * @param response
     * @param key
     */
    public static void removeCookie(HttpServletResponse response, String key) {
        setCookie(response, key, null, 0);
    }

    /**
     * 设置cookie
     *
     * @param response
     * @param name
     * @param value
     * @param maxAgeInSeconds
     */
    public static void setCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAgeInSeconds);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }
}
